//
//  settleViewController.swift
//  NewLndd
//
//  Created by 邵禹曦 on 2020/1/10.
//  Copyright © 2020 辽宁当代. All rights reserved.
//

import UIKit
import SwiftyJSON
// MARK: - 交收申请
class settleViewController: warehouseApiViewController {
    

    @IBOutlet weak var coi: UITextField!    // 商品代码
    @IBOutlet weak var ck: UITextField!     // 交货仓库
    @IBOutlet weak var jsjs: UITextField!// 交收件数
    @IBOutlet weak var jssl: UILabel!       //交收数量
    @IBOutlet weak var zdjsjs: UILabel!     // 最大交收件数
    @IBOutlet weak var thrq: UITextField!   //提货日期
    @IBOutlet weak var tj: UIButton!
    
    var whi : String? // 仓库编号
    
    var mode = ZZDatePicker.ZZDatePickerMode.default
    var _comgInfo = settlePicker()
    
    
    
    
    var _comInfo : String?
    override func viewDidLoad() {
        super.viewDidLoad()
        thrq.text = nowTime("yyyy-MM-dd HH:mm:ss")
        
        showInfo()
        
    }
    

}


extension settleViewController {
    private func showInfo() {
           // GCD
           let group = DispatchGroup()
    
           // 从沙盒中获取参数
            var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
            userPath =  (userPath as NSString).appendingPathComponent("data.plist")
            user = NSKeyedUnarchiver.unarchiveObject(withFile: userPath) as? User
Thread.sleep(forTimeInterval: 0.05)

           // 用户验证
           self.u = user?.U!
           self.retcode = user?.RETCODE!
           // 用户验证
           let str = [u,"101",retcode]
            
          // self.isLogin = self._network(str: str as! [String], group: group)
        group.enter()
        NetworkTools.share.check_user(code: str as Array<Any>) { (result, error) in
                      
                          if error != nil {
                              print("no no no")
                              return
                          }
                          

                          if Int(self._retcode(res: result!))! < 0 {
                              self.isLogin = false
                          } else {
                              self.isLogin = true
                          }
                          group.leave()
                      }

           group.notify(queue: DispatchQueue.main) {
               if !self.isLogin {
                if #available(iOS 13.0, *) {
                    self._alertVisitorView()
                }
                return
               } else {
                Thread.sleep(forTimeInterval: 0.05)
                   // 2.设置导航栏内容
                    //self.tableShouInfo()
                self.showCoiInfo()
                self.thrq.addTarget(self, action: #selector(self.selectDate(_:)), for: .touchDown)
               }
            }
       }
    
    // MARK: 获取当前时间
    // 这里的 type 是指日期的格式 “yyyyMMdd” 或者 “yyyy-MM-dd” 这样子
    func nowTime(_ type: String?) -> String {
        let currentDate = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = type ?? "yyyyMMdd"
        let time = formatter.string(from: currentDate)
        return time
    }
    
    @objc func selectDate(_ btn: UITextField) {
        ZZDatePicker.show(self, mode: mode) { [weak self] (date) in
            self?.mode.date = date
            let fmt = DateFormatter()
            fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
            btn.text = fmt.string(from: date)
        }
    }
}


// MARK: - 获取可交收的产品代码
extension settleViewController {
    private func showCoiInfo() {
        let group = DispatchGroup()
        let str = [user?.U!,user?.RETCODE! ]
        group.enter()
        NetworkTools.share.issue_enable_delivery_query(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            
            //print(resultArray)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) < 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "数据加载失败")
                            return self.setupVisitorView()
                        }
                    }
                }
            }
            
            
            let rstJson = JSON(resultArray)
            
            if self._comgInfo.COI != nil {
                self.coi.text = self._comgInfo.COI!
                self.jssl.text = self._comgInfo.DQ!
            } else {
                self.coi.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["COI"].stringValue )
                self.jssl.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["DQ"].stringValue )
            }
                
            
            
            
            group.leave()
            
        }
        
        group.notify(queue: DispatchQueue.main) {
            //self.psdm.addTarget(self, action: #selector(self.selectDate(_:)), for: .touchDown)
            // 查仓库
            self.showckInfo(coi : self.coi.text!)
        }
        
    }
    
    
    // 仓库
    private func showckInfo(coi : String) {
        let group = DispatchGroup()
        let str = [user?.U!,user?.RETCODE!, coi ]
        group.enter()
        NetworkTools.share.issue_warehouse_query(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            
            //print(resultArray)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) < 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "数据加载失败")
                            return self.setupVisitorView()
                        }
                    }
                }
            }
            
         
            let rstJson = JSON(resultArray)
            
            self.ck.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["WHN"].stringValue )
            self.zdjsjs.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["Q"].stringValue )
            self.whi = (rstJson["REP"]["RESULTLIST"]["REC"][0]["WHI"].stringValue )
            group.leave()
            
        }
        
        group.notify(queue: DispatchQueue.main) {
            self.coi.addTarget(self, action: #selector(self.tz(_:)), for: .touchDown)
            self.tj.addTarget(self, action: #selector(self.showSqInfo), for: .touchUpInside)
            // 申请
            //self.showckInfo(coi : self.coi.text!)
            
            
        }
        
        
        
    }
    
    @objc func tz(_ btn: UITextField) {

        self.performSegue(withIdentifier: "jsxl", sender: self._comgInfo)

    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // 买挂单
        if segue.identifier == "jsxl" {
            let secVC = segue.destination as! settlePickerViewController
            //if let IndexPath = sender as? putUpView {
            secVC._comgInfo = sender as? settlePicker
            //}
        }
        
     
    }
    
    //issue_delivery_apply
   @objc private func showSqInfo() {
        
        guard self.jsjs.text != "" else {
            if #available(iOS 13.0, *) {
                self.showMsgbox(_message: "交收件数不能为空")
            }
            return
        }
        let str = [user?.U!,user?.RETCODE!, self.coi.text!, self.whi , self.jsjs.text!, self.thrq.text!,""]
        NetworkTools.share.issue_delivery_apply(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            

            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            
            
            print(resultArray)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) > 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "请求成功")
                        }
                    } else {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "请求失败")
                        }
                    }
                }
            }
        
        }
    }
    
    
    
    
}
